import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
//全局守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // 获取存储中的token 
  const hasToken = getToken()
  //验证是否有token
  if (hasToken) {
    //有token     登录了又访问登录页面
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })//重定向到主页
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // 其他页面
      //判断有没有name 如果没有就要去请求 user/getInfo
      const hasGetName = store.getters.name
      if(hasGetName){
        next()//继续
      }else{
          // 请求 user/getInfo   
          try {
            // get user info
            //调用服务器的接口查询用户名  然后再继续放行
            await store.dispatch('user/getInfo') 
            next()
          } catch (error) {
            // remove token and go to login page to re-login
            await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
      }  
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
